package com.yinian.cart.controller;



import com.yinian.cart.entity.OrderList;
import com.yinian.cart.service.OrderList.OrderListService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController//把方法的返回值返回到页面上
@RequestMapping("/Order")
public class OrderController {
    @Autowired
    private OrderListService orderListService;

    @PostMapping("/getAllOrderList")
    public String getAllOrderList(@RequestBody String json) {
        JSONObject jsonObject = new JSONObject(json);
        int userAccount = jsonObject.getInt("userAccount");
        List<OrderList> list = orderListService.getAllOrderList(userAccount);
        JSONObject result = new JSONObject();
        if (list != null) {
            JSONArray jsonArray = new JSONArray();
            for (OrderList orderList : list) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("orderId", orderList.getOrderId());
                jsonObject1.put("productId", orderList.getProductId());
                jsonObject1.put("orderTime", orderList.getOrderTime());
                jsonObject1.put("orderPrice", orderList.getOrderPrice());
                jsonObject1.put("dataId", orderList.getDataId());
                jsonObject1.put("productCount", orderList.getProductCount());
                jsonArray.put(jsonObject1);
            }
            result.append("status","ok");
            result.append("data",jsonArray);
        }else{
            result.append("status","no");
        }
        return result.toString();
    }

    @PostMapping("/addOrder")
    public String addOrder(@RequestBody String json) {
        JSONObject jsonObject = new JSONObject(json);
        String productId = (String) jsonObject.get("productId");
        int productCount = (int) jsonObject.get("productCount");
        int userAccount = (int) jsonObject.get("userAccount");
        OrderList cartList = orderListService.addNewOrderList(productId, productCount, userAccount);
        JSONObject result = new JSONObject();
        if (cartList != null) {
            result.put("status", "ok");
        } else {
            result.put("status", "no");
        }
        System.out.println(result.toString());
        return result.toString();
    }
}
